var Q = require('q'),
	operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    workController = require('../../../CBO/server/controllers/Work.server.controller'),
    completePlanController = require('../../../ProduceWork/server/controllers/CompletePlan.server.controllers'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller');
//1,根据传入的barcode(eg:test12345)在条码主档表中找到条码主档ID
//2,在装配关系表中通过上步找到的条码主档ID==装配条码ID（AssemblyBarcode）
//，找到对应的条码主档ID（BarcodeMaster）
//3,获取芯片ID、出货批次、尺寸（扩展字段1）、物料号（关联物料档案获取）。


exports.getAssemblyBarcodeData = function(req, res) {
	var barcode = req.body.Parameter.Barcode;
  
    barcodeMasterController.findBarcodeMasterByBarcode(barcode, function(err, barcodeMaster){
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (barcodeMaster == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询主档失败';
            newErr.message = '条码不存在';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        if (barcodeMaster.QCStatus !== QCEnum.QCStatus.Qualified) {
        	var newErr = new Error();
        	newErr.leval = 9;
        	newErr.title = '非法条码';
        	newErr.message = '不是合格单品';
        	res.json({
        	    Data: null,
        	    Error: newErr
        	});
        	return;
        }
        if (barcodeMaster.Status === BarcodeEnum.BarcodeStatus.Complete) {
        	var newErr = new Error();
        	newErr.leval = 9;
        	newErr.title = '非法条码';
        	newErr.message = '该单品已完工';
        	res.json({
        	    Data: null,
        	    Error: newErr
        	});
        	return;
        }
        res.json({
        	Data: barcodeMaster,
        	Error: null
        });
    });
};

//获取工位和作业信息
exports.getLocationAndWork = function(req, res) {
	var deviceId = req.body.Parameter.DeviceId;

	findLocationAndWork(deviceId).then(function(result) {
		res.json(result);
	}, function(err) {
		res.json(err);
	});
};


exports.doStocking = function(req, res) {
	var parameter = req.body.Parameter,
	    wareHouseId = parameter.wareHouseId,
	    //包装货号
	    packagecode = parameter.Packagecode,
		//芯片ID集合
		barcodeMasters = parameter.barcodeMasters,
		//需要更新的数据
		ItemMaster = parameter.ItemMaster,
        Terminal = parameter.Terminal,
        TerminalName = parameter.TerminalName,
        Work = parameter.Work,
        WorkName = parameter.WorkName,
        WorkLocation = parameter.WorkLocation,
        WorkLocationName = parameter.WorkLocationName,
        userId = parameter.UserID;

    var packagecodeID = 0;
    var BizRecordRecords = [];  

	barcodeMasterController.insertPackageBarcode(packagecode, function(err, barcodeMaster){
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
        	packagecodeID = barcodeMaster._id;
        	// console.log("packagecodeID-----------"+packagecodeID);
            //根据物料和作业查找工序
		    operationController.findByItemMasterAndWork(ItemMaster, Work, function (err, operationRecord) {
		        if (err) {
		            res.json({
		                Data: null,
		                Error: err
		            });
		        }
		        else {
		            if (operationRecord == null) {
		                var newErr = new Error();
		                newErr.leval = 9;
		                newErr.title = '查询工序失败';
		                newErr.message = '该物料没有找到对应作业的工序！';
		                res.json({
		                    Data: null,
		                    Error: newErr
		                });
		            }
		            else {
		            	var bizRecords = [];
		            	var dateNow = Date.now();
		            	for (var i = 0; i < barcodeMasters.length; i++) {
		            		var barcodeMaster = barcodeMasters[i];
		            		bizRecords.push({
		            			CollectDateTime: dateNow,
					            Users: [userId],
					            // BusinessStatus: 1,//业务状态：完成
					            QCType: barcodeMaster.QCType,//质检类型：全检
					            QCUser: userId,
					            QCDateTime: dateNow,
					            QCStatus: barcodeMaster.QCStatus,
                                BarcodeMaster:barcodeMaster._id,
				                Work:Work,
				                WorkName:WorkName,
				                WorkLocation:WorkLocation,
				                WorkLocationName:WorkLocationName,
				                Terminal:Terminal,
				                TerminalName:TerminalName,
				                Operation:operationRecord._id,
				                OperationName:operationRecord.Name
		            		});
		            	};

		            	var bindContext = {
		                    Work: Work,
		                    WorkName: WorkName,
		                    User: userId,
		                    WorkLocation: WorkLocation,
		                    WorkLocationName: WorkLocationName
		                }
		                var barcodepromises = [];
		                barcodeMasters.forEach(function (barcodeMaster) {
		     
		                    barcodepromises.push(checkBizRecord(barcodeMaster.Barcode,operationRecord,bindContext));
		                        
		                });

		                Q.all(promises).then(function () {
                            bizRecordController.addBizRecords(bizRecords, function (err, BizRecords) {
	                            if (err) {
						            res.json({
						                Data: null,
						                Error: err
						            });
						        }
						        else{
						        	//条码更新数据数组
						        	BizRecordRecords = BizRecords[0].Insert;
						        	// console.log(BizRecords[0].Insert);
	                                var updateRecords = [];
								    for (var i = 0; i < BizRecords[0].Insert.length; i++) {
								    	var bizRecord = BizRecords[0].Insert[i];
								          updateRecords.push({
								          	_id: bizRecord.BarcodeMaster,
								            Users: bizRecord.Users,  
								            BizRecord: bizRecord._id,
								            Work: bizRecord.Work,
								            WorkName: bizRecord.WorkName,
								            WorkLocation: bizRecord.WorkLocation,
								            WorkLocationName: bizRecord.WorkLocationName,
								            Terminal: bizRecord.Terminal,
								            TerminalName: bizRecord.TerminalName,
								            Operation: bizRecord.Operation,
								            OperationName: bizRecord.OperationName
								          });    
								    };

						        	// updateRecords.forEach(function (updateRecord) {
							        //    updateRecord.Status = 4;
							        //    updateRecord.RowStatus = PublicEnum.RowStatus.Modify;
							        //    updateRecord.ModifyBy = updateRecord._id;
							        // });
	                                // console.log(updateRecords);
						        	barcodeMasterController.updateBarcodes(updateRecords, function(err, record){
						        		// console.log(err);
						        		// console.log(record);
	                                    if (err) {
								            res.json({
								                Data: null,
								                Error: err
								            });
								        }
								        else{
						                    barcodeMasterController.addPackageAssemblyRelations(packagecodeID,barcodeMasters,function(err, record){
	                                            if (err) {
										            res.json({
										                Data: null,
										                Error: err
										            });
										        }
										        else{
										            //查询更新后的多条条码主档信息(循环查)
										            var promises = [];
										            var updateBarcodeMasters = [];
										            //存入多个完工计划id
										            var completePlanIds = [];
												    barcodeMasters.forEach(function (barcodeMaster) {
												        promises.push(queryBarcodeMaster(barcodeMaster.Barcode).then(function(result) {
												        	       // console.log("--------------result-----------------");
												        	       // console.log(result);
												        	       // console.log("--------------result_id-----------------");
												        	       // console.log(result._id);
												        	       var dateNow = Date.now();
														           updateBarcodeMasters.push({
														           	   BarcodeMaster: result._id,
															           Barcode: result.Barcode,
															           RcvBusinessType: 0,
															           BusinessDocID: result.MO,
															           ItemMaster: result.ItemMaster,
															           RcvUser: result.Users[0],
															           RcvDateTime: dateNow,
															           RcvQty: 1,
															           RcvOperation: result.Operation,
															           BizRecord: result.BizRecord,
															           WareHouse: wareHouseId
														           });
	                                                               
	                                                               completePlanIds.push(result.CompletePlan);

														        }, function(err) {
														          
														        }));   
												    });
										        	Q.all(promises).then(function () {
										        		 // console.log(updateBarcodeMasters);
										        		 //创建入库记录
	                                                     barcodeMasterController.addPackageRecords(updateBarcodeMasters,userId,function(err, record){
		                                                    if (err) {
													            res.json({
													                Data: null,
													                Error: err
													            });
													        }
													        else{
													        	var completePlanPromises = [];
													        	completePlanIds.forEach(function (completePlanId) {
															        completePlanPromises.push(queryCompletePlan(completePlanId));   
															    });
	                                                            Q.all(completePlanPromises).then(function () {         
	                                                        		res.json({
														                Data: true,
														                Error: null
														            });
	                                                            }, function (err) {
	                                                            	res.json({
	                                                            	    Data: null,
	                                                            	    Error: err
	                                                            	});
	                                                            });
													        }
											        	});   
												              
												    }); 

										        	
										        }
						                    });
								        }
						            });
						        }
			            	});
		                });
		                 
		                
		            }
		        }
		    });
           
        }
    });
	
};

function checkBizRecord(barcode,operationRecord,bindContext){
	var deferred = Q.defer();
 
	findBarcodeMaster(barcode).then(function (record) {	                    
	    barcodeMasterController.streamValidation(record, operationRecord, bindContext).then(function (result){
	        deferred.resolve();
	    },function(error){
	        deferred.reject(err);
	    }); 
	},function(error){
	    deferred.reject(err);
	});
    
    return deferred.promise;
}

function findBarcodeMaster(barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (barcodeMaster == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '无法识别条码';
            newErr.message = '无法识别的条码，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(barcodeMaster);
    });

    return deferred.promise;
}

function queryBarcodeMaster (Barcode) {
    var deferred = Q.defer();
    barcodeMasterController.findBarcodeMasterByBarcode(Barcode, function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        else{
        	if (result) {
               deferred.resolve(result); 
            } 
        }            
    });  
    return deferred.promise;
}
//查找完工计划表中完工量
function queryCompletePlan (completePlanId) {
    var deferred = Q.defer();
    completePlanController.findCompletePlan(completePlanId, function (err, result) {
        if (err) {
            deferred.reject(err);
        } else {
        	if (result) {
        	   completePlanController.updateByValue(completePlanId,{CompleteQty:result.CompleteQty?result.CompleteQty+1:1}, function (errData, resultData) {
			        if (errData) {
			            deferred.reject(errData);
			        } else {
			        	if (resultData.ok===1&&result.CompleteQty+1 === result.Qty) {
			        	   	  completePlanController.updateByValue(completePlanId,{Status:2}, function (errStatus, resultStatus) {	   	  	    
							        if (errStatus) {
							            deferred.reject(errStatus);
							        } else {
							        	if (resultStatus) {
							        	   deferred.resolve(resultStatus); 
							            } 
							        }            
							  }); 
			        	} else {
			        		deferred.resolve(resultData); 
			        	}
			        } 		                  
			    });                 
            } else {
            	deferred.resolve(); 
            }
        }            
    });  
    return deferred.promise;
}

// //更新完工计划表数
// function updateCompletePlanNum (Barcode) {
//     var deferred = Q.defer();
//     barcodeMasterController.findBarcodeMasterByBarcode(Barcode, function (err, result) {
//         if (err) {
//             deferred.reject(err);
//             return;
//         }
//         else{
//         	if (result) {
//                deferred.resolve(result); 
//             } 
//         }            
//     });  
//     return deferred.promise;
// }


// //入库（包装条码 物件条码集合（查找到的芯片id） 设备id）
// function doDataStocking(packagecode, barcodeMasters, deviceId, deviceName, workId, workName, locationId, locationName, userId) {
// 	var deferred = Q.defer();
// 	var operation_Id = ''; //工序id
// 	var BizRecordIds = [];//流水ids
// 	barcodeMasterController.insertPackageBarcode(packagecode, function(err, barcodeMaster) {
// 		if (err) {
// 			deferred.reject(err);
// 			return;
// 		} else {
// 			if (barcodeMaster != null) {
// 				barcodeMasterController.updateBarcodes(barcodeMasters, function(err, record) {
// 					if (err) {
// 						deferred.reject(err);
// 						return;
// 					} else {
// 						if (record != null) {
// 							barcodeMasterController.insertBarcodesFlow(barcodeMasters, deviceId, deviceName, workId, workName, locationId, locationName, userId, function(err, record, operationId) {
// 								operation_Id = operationId;
// 								if (err) {
// 									deferred.reject(err);
// 									return;
// 								} else {
// 									if (record != null) {
// 										barcodeMasterController.insertPackageAssemblyRelation(packageBarcode, barcodeMasters, function(err, record) {
// 											if (err) {
// 												deferred.reject(err);
// 												return;
// 											} else {
// 												if (record != null) {
// 													barcodeMasterController.insertStockingRecord(barcodeMasters,userId, operation_Id,BizRecordIds, function(err, record) {
// 														console.log(record);
// 													});
// 												}

// 											}
// 										});
// 									}

// 								}
// 							});
// 						}

// 					}
// 				});
// 			}

// 		}
// 	});
// 	return deferred.promise;

// }

//获取装配条码的信息
function doAssemblyBarcodeData(barcode) {
	var deferred = Q.defer();
	barcodeMasterController.findAssemblyBarcodeMasterId(barcode, function(err, barcodeMaster) {
		if (err) {
			deferred.reject(err);
			return;
		} else {
			if (barcodeMaster._id) {
				barcodeMasterController.findAssemblyBarcodeMaster(barcodeMaster._id, function(err, barcodeMaster) {
					if (err) {
						deferred.reject(err);
						return;
					}
					if (barcodeMaster == null) {
						var newErr = new Error();
						newErr.leval = 9;
						newErr.title = '条码扫描失败';
						newErr.message = '该条码没有对应的条码主档！';
						deferred.resolve({
							Data: null,
							Error: newErr
						});
					} else {
						var result = {
							_id: barcodeMaster.BarcodeMaster._id,
							Barcode: barcodeMaster.BarcodeMaster.Barcode,
							ItemMasterCode: barcodeMaster.BarcodeMaster.ItemMasterCode,
							ShipLotNumber: barcodeMaster.BarcodeMaster.ShipLotNumber
						};
						deferred.resolve({
							Data: result,
							Error: null
						});
					}
					// deferred.resolve(barcodeMaster);
				});
			}
		}
	});
	return deferred.promise;
};
